package com.weixing.mall.provider.interceptor;

import com.weixing.mall.core.annotation.SysLog;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.utils.RequestUtil;
import com.weixing.mall.provider.api.model.dto.AccessLogDto;
import com.weixing.mall.provider.api.service.AccessLogRpcService;
import com.weixing.mall.util.ip.IpParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * The class Token interceptor.
 *
 * @author siashan
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    @Autowired
    private AccessLogRpcService accessLogRpcService;
    private SysLog sysLog = null;

    /**
     * Pre handle boolean.
     *
     * @param request  the request
     * @param response the response
     * @param handler  the handler
     *
     * @return the boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        this.sysLog = getSysLogAnno(handler);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        if (null != sysLog) {
            String uri = request.getRequestURI();
            //获取用户
            String userName = AuthUtil.getSysExt().getRealName();
            //获取用户id
            Long userId = AuthUtil.getSysExt().getUid();
            //获取用户ip
            String ipAddr = RequestUtil.getRemoteAddr(request);

            String remoteMac = "";

            //创建访问日志对象，并set属性
            AccessLogDto sysAccessLog = new AccessLogDto();
            sysAccessLog.setUserId(userId);
            sysAccessLog.setUserName(userName);
            sysAccessLog.setUserId(userId);
            sysAccessLog.setUserName(userName);
            sysAccessLog.setAccessUrl(uri);
            sysAccessLog.setIpLoc(IpParser.parse(ipAddr));
            sysAccessLog.setIpAddr(ipAddr);
            sysAccessLog.setMacAddr(remoteMac);
            sysAccessLog.setOperateType(sysLog.type().getValue());
            sysAccessLog.setOperateDesp(sysLog.desp());
            //保存访问日志到数据库
            accessLogRpcService.saveAccessLog(sysAccessLog);
        }
    }

    private SysLog getSysLogAnno(Object handler) {
        SysLog access = null;
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            access = handlerMethod.getMethodAnnotation(SysLog.class);
        }
        return access;
    }

}
